import {message} from 'antd';
import {getUploadAccessToken, upload} from '../services/api';

export default {
	namespace: 'upload',

	state: {
		access_token: '',
		url: ''
	},

	effects: {
		*fetchAccessToken(_, {call, put}) {
			const response = yield call(getUploadAccessToken);
			if (response.status === 'SUCCESS') {
				yield put({
					type: 'setData',
					payload: {
						access_token: response.data.access_token
					}
				});
			} else {
				message.error(response.failedMsg);
			}
		},
		*upload({
			payload
		}, {call, put}) {
			const response = yield call(upload, payload);
			if (response.code === 0) {
				yield put({
					type: 'setData',
					payload: {
						url: response.data.files.file.url
					}
				});
			} else {
				message.error(response.message);
			}
		}
	},

	reducers: {
		setData(state, {payload}) {
			return {
				...state,
				...payload
			};
		}
	}
};
